﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Web;

namespace gnet1.Models
{
  public class PushButtonGameViewModel
  {
    [Required(ErrorMessage = "Name is required.")]
    public string Name { get; set; }

    [Required(ErrorMessage = "Email is required.")]
    public string Email { get; set; }

    public long PushCounter { get; set; }
    public string Error { get; set; }
    private readonly string path = HttpContext.Current.Server.MapPath("~/test/pushcounter.txt");

    private Object thisLock = new Object();
    private readonly string ConnectionString;

    public PushButtonGameViewModel()
    {
      ConnectionString = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
    }

    public long GetCounter()
    {
      return 1000;
    }

    public long GetCounter(string name, string email)
    {
      try
      {
        using (var conn = new SqlConnection(ConnectionString))
        using (var cmd = new SqlCommand("dbo.UpdatePushCounter", conn))
        {
          conn.Open();

          // Stored Proc method
          cmd.CommandType = CommandType.StoredProcedure;
          cmd.Parameters.AddWithValue("@name", name);
          cmd.Parameters.AddWithValue("@email", name);
          SqlParameter retval = cmd.Parameters.AddWithValue("@id", SqlDbType.BigInt);
          retval.Direction = ParameterDirection.Output;
          cmd.ExecuteNonQuery();

          var outme = cmd.Parameters["@id"].Value;
          PushCounter = (Convert.ToInt64(outme));
          return PushCounter;
        }
      }
      catch (Exception ex)
      {
        return 1000;
      }
    }


    /*
    public void PushButtonGameViewModel1()
    {
      Error = "No Error";

      // Open File and read page counter value
      try
      {
        if (File.Exists(path))
        {
          string value1 = File.ReadAllText(path);
          PushCounter = long.Parse(value1);
         }
        else
        {
          using (StreamWriter sw = File.CreateText(path))
          {
            sw.WriteLine("0");
          }
          PushCounter = 1;
        }
      }
      catch (Exception ex)
      {
        PushCounter = 1;
        Error = ex.Message;
      }
    }

    public long GetCounter()
    {
      return PushCounter;
    }
  

    public void IncrementPushCounter()
    {
      lock (thisLock)
      {
        PushCounter++;
        UpdatePushCounterToDisk();
      }
    }
     *   */

    private void UpdatePushCounterToDisk()
    {
      try
      {
        File.WriteAllText(path, PushCounter.ToString());
      }
      catch (Exception ex)
      {
        Error = ex.Message;
      }
    }
  }
}